package com.beijiteshop.shop.ui.order.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.beijiteshop.libcommon.base.adapter.showEmpty
import com.beijiteshop.libcommon.base.adapter.showError
import com.beijiteshop.libcommon.base.adapter.showLoading
import com.beijiteshop.libcommon.base.adapter.showNetError
import com.beijiteshop.libcommon.ext.databinding.bindView
import com.beijiteshop.libcommon.ext.databinding.inflateBinding
import com.beijiteshop.libcommon.utils.EventUtil
import com.beijiteshop.shop.R
import com.beijiteshop.shop.base.BaseContainerFragment
import com.beijiteshop.shop.data.DataServer
import com.beijiteshop.shop.databinding.FragmentOrderDetailBinding
import com.beijiteshop.shop.databinding.HeaderOrderDetailBinding
import com.beijiteshop.shop.model.api.response.OrderDetailBean
import com.beijiteshop.shop.model.api.response.RefundBean
import com.beijiteshop.shop.model.entity.RefundEntity
import com.beijiteshop.shop.model.event.EventKey
import com.beijiteshop.shop.ui.order.adapter.OrderDetailInfoAdapter
import com.beijiteshop.shop.ui.order.adapter.OrderRefundAdapter
import com.beijiteshop.shop.ui.order.vm.OrderVM
import org.koin.android.viewmodel.ext.android.viewModel

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/11 18:29
 * @Description 订单详情
 */
class OrderDetailFragment : BaseContainerFragment(R.layout.fragment_order_detail){

    companion object{
        const val BUNDLE_ORDER_ID = "order_id"

        fun newInstance(orderId: String): OrderDetailFragment{
            return OrderDetailFragment().apply {
                arguments = Bundle().apply {
                    putString(BUNDLE_ORDER_ID,orderId)
                }
            }
        }
    }

    private val mBinding by bindView<FragmentOrderDetailBinding>()
    private val mOrderDetailVM: OrderVM by viewModel()
    private var mOrderId: String? = null
    private var mDetailAdapter = OrderDetailInfoAdapter(mutableListOf())
    private var mOrderDetailBean: OrderDetailBean? = null

    private lateinit var mOrderDetailHeaderBinding: HeaderOrderDetailBinding

    private val mRefundDialog: OrderRefundDialog by lazy {
        OrderRefundDialog()
    }

    override fun onLazyLoad() {
        requestData()
    }

    override fun initView(view: View) {
        mBinding.orderDetailTitleBar.titleBarTitleTv.text = resources.getString(R.string.order_detail)
        mBinding.orderDetailTitleBar.titleBarBackIv.setOnClickListener {
            close()
        }
        initHeaderView()
        initRV()
    }

    override fun initData() {
        mOrderId = arguments?.getString(BUNDLE_ORDER_ID)
    }

    override fun initEvent() {
        startObserve()

        mOrderDetailHeaderBinding.orderRefundBtn.setOnClickListener {
            showRefundDialog()
        }

        EventUtil.observe<Any>(this,EventKey.REFUND_COMMIT){
            requestData()
        }
    }

    private fun initRV(){
        mDetailAdapter.addHeaderView(mOrderDetailHeaderBinding.root)

        mBinding.orderDetailRv.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = mDetailAdapter
        }
    }

    private fun initHeaderView(){
        mOrderDetailHeaderBinding = inflateBinding(LayoutInflater.from(requireContext()))
    }

    private fun startObserve(){
        mOrderDetailVM.apply {
            liveOrderDetail.observeKt { orderDetailBean ->
                if (orderDetailBean != null){
                    mOrderDetailBean = orderDetailBean
                    mOrderDetailHeaderBinding.detail = orderDetailBean
                    mDetailAdapter.setNewInstance(orderDetailBean.groupGoods.toMutableList())
                    if (!orderDetailBean.bus_Refund.isNullOrEmpty()){
                        setRefundList(orderDetailBean.bus_Refund)
                    }
                }
            }

            liveNetError.observeKt {
                mDetailAdapter.showNetError(it){
                    requestData()
                }
            }

            liveError.observeKt {
                mDetailAdapter.showError(it){
                    requestData()
                }
            }

            liveEmpty.observeKt {
                mDetailAdapter.showEmpty(it){
                    requestData()
                }
            }
        }
    }

    private fun requestData(){
        mOrderId?.let {
            mDetailAdapter.showLoading()
            mOrderDetailVM.getOrderDetailInfo(it)
        }
    }

    private fun showRefundDialog(){
        if (mOrderDetailBean != null){
            mRefundDialog.showDialog(childFragmentManager,mOrderDetailBean!!)
        }
    }

    private fun setRefundList(data: List<RefundBean>?){
        if (!data.isNullOrEmpty()){
            val list = mutableListOf<RefundEntity>()
            data.forEach {
                list.add(RefundEntity(it.createTime,getRefundReason(it)))
                list.add(RefundEntity(getRefundState(it),null))
            }
            val refundAdapter = OrderRefundAdapter(list)
            mOrderDetailHeaderBinding.orderRefundRv.apply {
                visibility = View.VISIBLE
                layoutManager = LinearLayoutManager(requireContext())
                adapter = refundAdapter
            }
        }
    }

    private fun getRefundState(refundBean: RefundBean): String{
        return when(refundBean.status){
            "0" -> {//处理中
                resources.getString(R.string.in_process)
            }
            "1" -> {//退款成功
                resources.getString(R.string.refund_successful)
            }
            "2" -> {//退款失败
                resources.getString(R.string.refund_failed)
            }
            else -> {//默认是时间字符串
                refundBean.createTime
            }
        }
    }

    private fun getRefundReason(refundBean: RefundBean): String{
        val format = resources.getString(R.string.refund_format)
        return String.format(format,refundBean.refund_Money,refundBean.reason)
    }
}